<template>
  <!-- 拓扑图工具条 -->
  <span>
    <div class="btn-group el_btn_tool">
      <!-- 选中 -->
      <el-tooltip content="选中" placement="top" >
        <button id="topo-select" class="btn icon_btn icon_min el-tooltip">
          <i class="i_default"></i>
        </button>
      </el-tooltip>

      <!-- 拖动 -->
      <el-tooltip content="拖动" placement="top" >
        <button id="topo-drag" class="btn icon_btn icon_min el-tooltip">
          <i class="i_drag"></i>
        </button>
      </el-tooltip>
      <!-- 缩小 -->
      <el-tooltip content="缩小" placement="top">
        <button id="topo-zoomin" class="btn icon_btn icon_min el-tooltip">
          <i class="i_zoomin"></i>
        </button>
      </el-tooltip>
      <!-- 放大 -->
      <el-tooltip content="放大" placement="top">
        <button id="topo-zoomout" class="btn icon_btn icon_min el-tooltip">
          <i class="i_zoomout"></i>
        </button>
      </el-tooltip>
      <!-- 水平居中对齐 -->
      <el-tooltip content="水平居中对齐" placement="top">
        <button id="topo-horizontal-align" class="btn icon_btn icon_min el-tooltip">
          <i class="i_horizontalalign"></i>
        </button>
      </el-tooltip>
      <!-- 垂直居中对齐 -->
      <el-tooltip content="垂直居中对齐" placement="top">
        <button id="topo-vertical-align" class="btn icon_btn icon_min el-tooltip">
          <i class="i_verticalalign"></i>
        </button>
      </el-tooltip>
      <!-- 适应内容 -->
      <el-tooltip content="适应内容" placement="top">
        <button id="topo-fitcontent" class="btn icon_btn icon_min el-tooltip">
          <i class="i_zoom"></i>
        </button>
      </el-tooltip>
    </div>
    <div class="btn-group">
      <!-- 导出图片 -->
      <el-tooltip content="导出图片" placement="top">
        <button id="topo-exportimg" class="btn icon_btn icon_min el-tooltip">
          <i class="i_img"></i>
        </button>
      </el-tooltip>
    </div>
    <div class="btn-group">
      <!-- 拓扑图新增 -->
      <el-tooltip content="拓扑图新增" placement="top">
        <button id="bus-topo-add" class="btn icon_btn icon_min el-tooltip">
          <i class="icon_add"></i>
        </button>
      </el-tooltip>
      <!-- 拓扑图删除 -->
      <el-tooltip content="拓扑图删除" placement="top">
        <button id="bus-topo-delete" class="btn icon_btn icon_min el-tooltip">
          <i class="i_delete"></i>
        </button>
      </el-tooltip>
      <!-- 导入设备 -->
      <el-tooltip content="导入设备" placement="top">
        <button id="bus-topo-import-device" class="btn icon_btn icon_min el-tooltip">
          <i class="icon_import"></i>
        </button>
      </el-tooltip>
      <!-- 拓扑扫描 -->
      <el-tooltip content="拓扑扫描" placement="top">
        <button id="bus-topo-scan" class="btn icon_btn icon_min el-tooltip">
          <i class="icon_scan"></i>
        </button>
      </el-tooltip>
      <!-- 新增连接 -->
      <el-tooltip content="新增连接" placement="top">
        <button id="bus-topo-add-link" class="btn icon_btn icon_min el-tooltip">
          <i class="icon_add"></i>
        </button>
      </el-tooltip>
      <!-- 删除拓扑图元素 -->
      <el-tooltip content="删除拓扑图元素" placement="top">
        <button id="topo-delete-map-element" class="btn icon_btn icon_min el-tooltip">
          <i class="i_delete"></i>
        </button>
      </el-tooltip>
    </div>
    <!-- 弹出对话框  -->
    <div id="bus-topo-dialog" style="display:none">
      <component :is="currentViewComp" transition="fade" transition-mode="out-in" keep-alive 
        :graphView="graphView"
      @transferNewSysmap="transferNewSysmap" @transferCloseDialog="transferCloseDialog" @transferCheckedNodes="transferCheckedNodes" :busType="busType"></component>
    </div>
  </span>
</template>
<script>
import topoApi from 'api/topo'
import iconApi from 'api/config/iconmanager'
import eventHubs from 'common/eventHubs'
import busTopoAddComp from 'views/topo/topoCreate.vue'
import deviceTreeComp from 'views/device/deviceTree.vue'
import art from 'utils/artdialog'
import { CreateEdgeInteractor } from 'common/topo/CreateEdgeInteractor.js'
import { createNode } from 'common/topo/addTopoElement.js'
import btnEvent from 'common/topo/btnEvent'
import topoScanComp from 'views/topo/topoScan.vue'
export default {
  data() {
    return {
      value: '',
      topoBaseInfo: [],
      bustopoDialog: null,
      busType: '1',
      currentViewComp: null,
      graphView: null,
      imageAndHostidMap: {},
    }
  },
  components: {
    busTopoAddComp, deviceTreeComp, topoScanComp
  },
  computed: {
    sysIcons() {
      return this.$store.state.topo.sysIcons;
    },
    defaultNodeImg(){
      return this.$store.state.topo.defaultNodeImg;
    }
  },
  mounted() {
    const sysmapidTmp = this.$route.query.sysmapid;
    if (sysmapidTmp != undefined && sysmapidTmp != null) {
      this.value = sysmapidTmp;
    }
    this.addEventListener();
    this.initImageAndHostidMap();
  },
  methods: {
    initImageAndHostidMap() {
      const self = this;
      iconApi.getImageAndHostid().then(response => {
        self.imageAndHostidMap = response.data;
      });
    },
    layout() {
      const self = this;
      // 布局设置
      const autoLayout = new ht.layout.AutoLayout(this.graphView);
      // this.autoLayout.setAnimate(animate);
      autoLayout.layout('symmetric', function() {
        self.graphView.fitContent(true);
      });
    },
    transferCheckedNodes(checkedNodes) {
      const self = this;
      let selements = [];
      const sysmapid = this.$store.state.topo.sysmapid;
      const dataModel = this.graphView.getDataModel();

      // api添加记录
      $.each(checkedNodes, function() {
        const etype = this.type;
        if (etype == 2) {
          let element = {};
          element.label = this.host;
          element.elementid = this.id;
          element.sysmapid = sysmapid;
          element.elementtype = "0";
          const sysimage = self.imageAndHostidMap[this.hostid];
          if (!self.isObjBlank(sysimage)) {
            element.iconid_off = sysimage.imageid;
          } else {
            element.iconid_off = "150";
          }
          element.x = 200;
          element.y = 200;
          selements.push(element);
        }
      });
      //使用过滤函数过滤数组元素 过滤函数必须返回 true 以保留元素或 false 以删除元素。
      let result = $.grep(selements, function(ele){
          let flag = true
          dataModel.each(function(node,index){
            let data = node.getAttr('data')
            if(ele.elementid == data.elementid){
              flag = false
              return
            }
          })
          return flag
      });
      if(result.length == 0){
          self.$message('拓扑图中已存在选中元素！');
          self.closeDialog();
          return
      }
      topoApi.createMapElement(result).then(response => {
        if (response.status == 200) {
          const elementData = response.data;
          $.each(elementData, function() {
            // 创建图形元素
            var newNode = createNode(this, self.sysIcons,self.defaultNodeImg)
            dataModel.add(newNode);
          });
          self.layout(); // 重新自动布局
          self.closeDialog();
          self.$message(self.$t('Created Successfully'));
        }
      }).catch(err => {
        self.$message.error(self.$t('Failed to create'));
      });
    },
    transferCloseDialog(msg) {
      this.closeDialog();
      this.$message(msg);
    },
    closeDialog() {
      if (this.bustopoDialog != null) {
        this.bustopoDialog.close();
      }
    },
    transferNewSysmap(newSysmap) {
      if (newSysmap != null && newSysmap != undefined) {
        this.topoBaseInfo.push(newSysmap);
      }
      if (this.bustopoDialog != null) {
        this.bustopoDialog.close();
      }
      this.$message(this.$t("Created Successfully"));
    },
    addEventListener() {
      const self = this;
      // 事件处理
      eventHubs.getEventHub().$on('topoGraphView', (topoGraphView) => { //Hub接收事件
        self.graphView = topoGraphView;
      });
      $('.el_btn_tool button').on('click',function(e){
          $('.el_btn_tool button').removeClass('active')
          $(this).addClass('active')
      });
      $('#topo-toolbar').on('click', '#topo-select', function() {
          self.graphView.setEditable(false)
      });

      $('#topo-toolbar').on('click', '#topo-drag', function() {
          self.graphView.setEditable(true)
      });

      $('#topo-toolbar').on('click', '#topo-zoomin', function() {
        self.graphView.zoomOut(true);
      });

      $('#topo-toolbar').on('click', '#topo-zoomout', function() {
        self.graphView.zoomIn(true);
      });

      $('#topo-toolbar').on('click', '#topo-fitcontent', function() {
        self.graphView.fitContent(true);
      });
      //水平居中对齐
      $('#topo-toolbar').on('click', '#topo-horizontal-align', function() {
        // 布局设置
        const autoLayout = new ht.layout.AutoLayout(self.graphView);
        // this.autoLayout.setAnimate(animate);
        autoLayout.layout('hierarchical', function() {
          self.graphView.fitContent(true);
        });
      });
      //垂直居中对齐
      $('#topo-toolbar').on('click', '#topo-vertical-align', function() {
        // 布局设置
        const autoLayout = new ht.layout.AutoLayout(self.graphView);
        // this.autoLayout.setAnimate(animate);
        autoLayout.layout('towardeast', function() {
          self.graphView.fitContent(true);
        });
      });

      $('#topo-toolbar').on('click', '#topo-exportimg', function() {
        const doc = window.open().document;
        doc.open();
        doc.write("<img src='" + self.graphView.toDataURL() + "'/>");
        doc.close();
        doc.body.style.margin = '0';
        doc.title = 'Export image at ' + new Date();
      });

      // 工具栏按钮事件
      // 新增拓扑图
      $('#topo-toolbar').on('click', '#bus-topo-add', function() {
          console.log('新增拓扑图')
        self.currentViewComp = busTopoAddComp;
        self.bustopoDialog = art.artdialog(self.$t('New Business'), $('#bus-topo-dialog'), 300, 150, 'bustopodialog');
      });
      // 删除拓扑图
      $('#topo-toolbar').on('click', '#bus-topo-delete', function() {
          console.log('删除拓扑图')
        self.$confirm(self.$t('Are you sure delete?', [self.value]), self.$t('Prompt'), {
          type: 'warning'
        }).then(() => {
          topoApi.deleteSysmap(self.value).then(response => {
            self.$message({
              type: 'success',
              message: self.$t('Deleted Successfully')
            });
          }).catch(error => {
            self.$message({
              type: 'error',
              message: self.$t('Failed to delete')
            });
          });
        }).catch(() => {
          self.$message({
            type: 'info',
            message: self.$t('Cancel to delete')
          });
        });
      });

      // 导入设备
      $('#topo-toolbar').on('click', '#bus-topo-import-device', function() {
          console.log('导入设备')
        self.currentViewComp = deviceTreeComp;
        self.importDeviceDialog = art.artdialog(self.$t('Import Device'), $('#bus-topo-dialog'), 400, 500, 'importdevicedialog');
      });

      // 新增连接
      $('#topo-toolbar').on('click', '#bus-topo-add-link', function() {
          console.log('新增连接')
        const message = { success: self.$t('Created Successfully'), failed: self.$t('Failed to create') };
        btnEvent.topoAddLink(self.graphView, self.value, message);
      });

      // 删除拓扑图元素
      $('#topo-toolbar').on('click', '#topo-delete-map-element', function() {
          console.log('删除拓扑图元素')
          const message = { success: self.$t('Deleted Successfully'), failed: self.$t('Failed to delete'), info: self.$t('Cancel to delete') };
          btnEvent.deleteMapElement(self.graphView, message);
      });

      // 拓扑扫描，自动发现拓扑图
      $('#topo-toolbar').on('click', '#bus-topo-scan', function() {
          console.log('拓扑扫描，自动发现拓扑图')
        self.currentViewComp = topoScanComp;
        self.topoScanDialog = art.artdialog(self.$t('Topo Scan'), $('#bus-topo-dialog'), 600, 450, 'toposcandialog');
      });
    },
    isObjBlank(obj) {
      return (obj === null) || (obj === undefined) || (obj === '');
    }
  }
}
</script>
<style scoped>
 .el_btn_tool .active {
  color: #1d90e6;
  border-color: #1d90e6;
  outline: 0;
  background-color: #20A0FF !important;
}
</style>
